package com.zgl.modules.order.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zgl.modules.goods.DTO.GoodsDTO;
import com.zgl.modules.goods.entity.GoodsEntity;
import com.zgl.modules.goods.service.Impl.GoodsServiceImpl;
import com.zgl.modules.order.DTO.OrderDTO;
import com.zgl.modules.order.entity.OrderEntity;
import com.zgl.modules.order.mapper.OrderMapper;
import com.zgl.modules.order.service.OrderService;

import com.zgl.modules.user.entity.User;
import com.zgl.modules.user.service.impl.UserServiceImpl;
import com.zgl.modules.wallet.entity.WalletEntity;
import com.zgl.modules.wallet.service.impl.WalletServiceImpl;
import com.zgl.utils.Params;
import com.zgl.utils.R;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.CookieValue;
import org.springframework.web.bind.annotation.RequestBody;

import javax.annotation.Resource;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;

@Service

public class OrderServiceImpl implements OrderService {
    @Resource
    private OrderServiceImpl orderService;
    @Resource
    private UserServiceImpl userService;
    @Resource
    private GoodsServiceImpl goodsService;
    @Resource
    private WalletServiceImpl walletService;
    @Resource
    OrderMapper orderMapper;

    public R savaOne(OrderEntity orderEntity) {
        if (1 == orderMapper.insert(orderEntity)) {
            return R.success();
        } else {
            return R.error("操作失败");
        }
    }
    public R queryOorderByName(OrderDTO orderDTO) {
        final String headerToken = orderDTO.getToken();
        Claims claims = Jwts.parser().setSigningKey("zgl-key").parseClaimsJws(headerToken).getBody();
        String tokenUserId = (String) claims.get("userid");
        int itokenUserId=Integer.parseInt(tokenUserId);
        QueryWrapper<OrderEntity> queryWrapper = new QueryWrapper<>() ;
        queryWrapper.and(wq -> {
                wq.and(wq0 -> wq0.like("goods_name", orderDTO.getName()));
                wq.and(wq1 -> wq1.eq("userid",tokenUserId));
                wq.and(wq2 -> wq2.eq("delete_status", "0"));
        });
//        queryWrapper.like("goods_name",orderDTO.getGoodsName()).eq("userid",tokenUserId).eq("delete_status",0);
        List<OrderEntity> OrderEntityList=orderMapper.selectList(queryWrapper);
        int currentPage= orderDTO.getCurrentPage().equals(null)?1:orderDTO.getCurrentPage();
        int pageSize =orderDTO.getSize().equals(null)?10:orderDTO.getSize();
        List<OrderEntity>ordersDTOS=new ArrayList<>();
        int total=0;
        if (OrderEntityList!=null) {
            total=OrderEntityList.size();
            int startRow = 0;
            int endRow = 0;

            if (total != 0) {
                startRow = (currentPage - 1) * pageSize + 1;
                endRow = currentPage * pageSize;
                if (endRow > total) {
                    endRow = total;
                }
                for (int i = startRow - 1; i < endRow; i++) {
                    ordersDTOS.add(OrderEntityList.get(i));
                }
            }
        }
        Map<String,Object> page=new HashMap<>();
        page.put("CurrentPage",currentPage);
        page.put("total",total);
        page.put("orders",ordersDTOS);
        return R.success(page);
    }
    public R removeOne(Integer id) {
        if (1 == orderMapper.deleteById(id)) {
            return R.success();
        } else {
            return R.error("操作失败");
        }
    }

    public R modifyOne(OrderEntity OrderEntity) {
        if (orderMapper.updateById(OrderEntity) == 1) {
            return R.success();
        } else {
            return R.error();
        }

    }

    public R getOne(Integer id) {
        OrderEntity OrderEntity = orderMapper.selectById(id);
        return R.success(OrderEntity);
    }
    @Override
    public R querOrderAsc(OrderDTO orderDTO) {
        int total=0;
        QueryWrapper<OrderEntity> queryWrapper = new QueryWrapper<>();
        List<OrderEntity> goodsEntityList = orderMapper.selectList(queryWrapper);
        int currentPage= orderDTO.getCurrentPage().equals(null)?1:orderDTO.getCurrentPage();
        int pageSize = orderDTO.getSize().equals(null)?10:orderDTO.getSize();
        List<OrderEntity>orderDTOS=new ArrayList<>();
        if (goodsEntityList!=null) {
            total=goodsEntityList.size();
            int startRow = 0;
            int endRow = 0;

            if (total != 0) {
                startRow = (currentPage - 1) * pageSize + 1;
                endRow = currentPage * pageSize;
                if (endRow > total) {
                    endRow = total;
                }
                for (int i = startRow - 1; i < endRow; i++) {
                    orderDTOS.add(goodsEntityList.get(i));
                }
            }
        }
        Map<String,Object> page=new HashMap<>();
        page.put("CurrentPage",currentPage);
        page.put("total",total);
        page.put("data",orderDTOS);
        return R.success(page);
    }
    @Override
    public R getOrderByUserId(Integer id, Params params) {
        QueryWrapper<OrderEntity> queryWrapper = new QueryWrapper<>() ;
        queryWrapper.eq("userid",id);
        queryWrapper.eq("delete_status","0");
        List<OrderEntity> OrderEntityList = orderMapper.selectList(queryWrapper);
        OrderDTO orderDTO =(OrderDTO) params.getParams();
        int currentPage= orderDTO.getCurrentPage().equals(null)?1:orderDTO.getCurrentPage();
        int pageSize =orderDTO.getSize().equals(null)?10:orderDTO.getSize();
        List<OrderEntity>ordersDTOS=new ArrayList<>();
        int total=0;
        if (OrderEntityList!=null) {
            total=OrderEntityList.size();
            int startRow = 0;
            int endRow = 0;

            if (total != 0) {
                startRow = (currentPage - 1) * pageSize + 1;
                endRow = currentPage * pageSize;
                if (endRow > total) {
                    endRow = total;
                }
                for (int i = startRow - 1; i < endRow; i++) {
                    ordersDTOS.add(OrderEntityList.get(i));
                }
            }
        }
        Map<String,Object> page=new HashMap<>();
        page.put("CurrentPage",currentPage);
        page.put("total",total);
        page.put("orders",ordersDTOS);
        return R.success(page);
    }
//    创建订单
    @Transactional
    public R createOrder(@RequestBody OrderDTO orderDTO){
        final String headerToken = orderDTO.getToken();
        Claims claims = Jwts.parser().setSigningKey("zgl-key").parseClaimsJws(headerToken).getBody();
        String tokenUserId = (String) claims.get("userid");
        int itokenUserId=Integer.parseInt(tokenUserId);
        User myUser=(User)userService.getOne(itokenUserId).getData();
        WalletEntity myWalletEntity=(WalletEntity) walletService.getCardByUserId(itokenUserId).getData();
        double balance=Double.valueOf(myWalletEntity.getBalance());
        double price=Double.valueOf(orderDTO.getGoodsPrice());
        if(balance-price<0){
            return R.error("钱包，余额不足，请充值！");
        }
        myWalletEntity.setBalance(String.valueOf(balance-price));
        walletService.modifyOne(myWalletEntity);
        GoodsEntity goodsEntity= (GoodsEntity) goodsService.getOne(orderDTO.getGoodsId()).getData();
        if(goodsEntity==null){
            return R.error("商品异常");
        }
        OrderEntity orderEntity=new OrderEntity();
        BeanUtils.copyProperties(orderDTO, orderEntity);
        BeanUtils.copyProperties(goodsEntity, orderEntity);
        orderEntity.setUsername(myUser.getUsername());
        orderEntity.setUserid(myUser.getId());
        orderEntity.setDate(new Date());
        orderEntity.setId(null);
        orderEntity.setGoodsId(String.valueOf(goodsEntity.getId()));
        orderEntity.setStatus("正常");
        orderEntity.setGoodsPrice(orderDTO.getGoodsPrice());
        orderEntity.setProfit("0");
        return orderService.savaOne(orderEntity);
    }
    //用户删除订单
    @Transactional
    public R deleteOrder(@RequestBody OrderDTO orderDTO){
        //将删除属性设为1
        orderDTO.setDeleteStatus("1");
        OrderEntity orderEntity=new OrderEntity();
        BeanUtils.copyProperties(orderDTO, orderEntity);
        return orderService.modifyOne(orderEntity);
    }
    //出售订单
    @Transactional
    public R sellProducts(@RequestBody OrderDTO orderDTO){
        final String headerToken = orderDTO.getToken();
        Claims claims = Jwts.parser().setSigningKey("zgl-key").parseClaimsJws(headerToken).getBody();
        String tokenUserId = (String) claims.get("userid");
        int itokenUserId=Integer.parseInt(tokenUserId);
        //将删除属性设为1
        Calendar cal = Calendar.getInstance();
        //Date类型的当前时间
        Date currentTimeD=cal.getTime();
        //Date类型的订单创建时间
        Date createTimeD =null;
        //可交易日期
        Date expirationTime=null;
        OrderEntity myOrderEntity=(OrderEntity)orderService.getOne(orderDTO.getId()).getData();
        int term=myOrderEntity.getGoodsTerm();

        createTimeD=myOrderEntity.getDate();
        cal.setTime(createTimeD);
        cal.add(Calendar.MONTH, term);
        expirationTime = cal.getTime();

//        if(expirationTime.after(currentTimeD)){
//            return R.error("商品期限未到，无法出售");
//        }
        double price = Double.valueOf(myOrderEntity.getGoodsPrice());
        double profit = Double.valueOf(myOrderEntity.getProfit());
        WalletEntity myWalletEntity=(WalletEntity) walletService.getCardByUserId(itokenUserId).getData();
        double balance = Double.valueOf(myWalletEntity.getBalance());
        myWalletEntity.setBalance(String.valueOf(balance+profit+price));
        try {
            walletService.modifyOne(myWalletEntity);
        }catch (Exception e){
            return R.error("出售产品失败，请联系客服");
        }
        OrderEntity orderEntity=new OrderEntity();
        BeanUtils.copyProperties(orderDTO, orderEntity);
        myOrderEntity.setDeleteStatus("1");
        myOrderEntity.setStatus("已售出");
        return orderService.modifyOne(myOrderEntity);}



}
